<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
          <span slot="before">共{{page.total}}条记录</span>
          <template slot="after">
            <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
            <el-button size="small" type="danger" @click="exportData">导出</el-button>
            <el-button size="small" type="primary" @click="showDialog = true" :disabled='!checkPermission("POINT-USER-ADD")'>新增员工</el-button>
          </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card :loading ='loading'>
        <!-- table表格 -->
        <el-table border :data='list'>
          <el-table-column type='index' label="序号" sortable="" align ='center'/>
          <el-table-column prop="username" label="姓名" sortable="" align ='center'/>
          <el-table-column prop="staffPhoto" label="头像" sortable="" align ='center'>
            <template slot-scope="{row}">
                <!-- {{row.staffPhoto}} -->
                <!-- <img :src="row.staffPhoto" class="user-avatar" alt="" v-imageerror ="defaultImg" /> -->
                 <!-- <el-avatar :src="row.staffPhoto"  v-imageerror ="defaultImg"/> -->
                 <el-avatar :size="60" >
                  <img :src="row.staffPhoto" alt="" v-imageerror ="defaultImg"  @click="showQrCode(row.staffPhoto)" /> 
                </el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="workNumber"  label="工号" sortable="" align ='center'/>
          <el-table-column prop="formOfEmployment" :formatter='formatEmployment' label="聘用形式" sortable="" align ='center'/>
          <el-table-column prop="departmentName"  label="部门" sortable="" align ='center'/>
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="" align ='center'>
            <template slot-scope="{row}">
                {{row.timeOfEntry | formatDate}}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="" align ='center'>
            <!-- <template v-slot="{row}"> -->
              <el-switch slot-scope="{row}" :value='row.enableState === "1"'/>
            <!-- </template> -->
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280" align ='center'>
            <template v-slot= "{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size='page.size' :total ='page.total' :current-page ='page.page' @current-change='changePage'></el-pagination>
        </el-row>
      </el-card>
    </div>
    <!-- 弹出层（将canvas标签放到dialog的弹层中） -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 弹出层 -->
    <add-employee :showDialog.sync="showDialog" />
    <!-- 放置分配组件 -->
    <assign-role :showRoleDialog.sync="showRoleDialog" :userId="userId" ref="assignRole"/>
  </div>
</template>

<script>
import img from '@/assets/common/head.jpg'
import {getEmployeeList, delEmployee} from '@/api/employee'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import {formatDate} from '@/filters'
import AssignRole from './components/assign-role.vue'
import QrCode from 'qrcode'
export default {
  data () {
    return {
      list:[], //接收rows
      page:{
        page: 1,  //页码
        size: 10, //每页条数
        total: 0
      },
      defaultImg : img,
      loading:false,
      showDialog: false, //控制弹出层的显示和隐藏
      showCodeDialog:false, //控制二维码弹出层
      showRoleDialog: false, //显示分配角色的弹层
      userId: null
    }
  },
  components: {
      AddEmployee,
      AssignRole
  },
  created () {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList(){
      this.loading = true
      const {rows,total} = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    changePage(newPage){
      this.page.page = newPage
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index){
    // 格式化聘用形式
     const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
   async deleteEmployee(id){
      try {
       await this.$confirm('您确定要删除吗？')
       await delEmployee(id)
       this.getEmployeeList()
       this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error);
      }
    },
    // 导出excel
   async exportData(){
       // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // data数据
      const {rows} = await getEmployeeList({page:1,size:this.page.total})
      const data = this.formatJson(headers , rows)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']] 
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 懒加载
      import('@/vendor/Export2Excel').then( excle => {
        excle.export_json_to_excel({
          header: Object.keys(headers),
          data, //[[]]要拿到所有的数据，没有方法可以拿到所有的数据，我们可以让一页展示所有的数据来拿到所有的数据，让size=total
          filename:'员工信息表',
          multiHeader, //复杂表头
           merges // 合并选项
        })
      
      })
    },
    // 转换rows的格式
    formatJson(headers , rows){
     return rows.map(item => {
         return Object.keys(headers).map(key => {
          if(headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime'){
              return formatDate(item[headers[key]]) // 返回格式化之前的时间
          }else if(headers[key] === 'formOfEmployment'){
              var obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }else{
            return item[headers[key]] 
          }
          })
       })
       
    },
    // 将图片url转换成二维码
   async showQrCode(url){
        // console.log(url);
        if(url){
         await (this.showCodeDialog = true) // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
          // console.log(this.$refs.myCanvas);
          QrCode.toCanvas(this.$refs.myCanvas,url)
        
        }else{
          this.$message.warning('该用户还未上传头像')
        }
    },
    // 编辑角色  
   async editRole(id){
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(this.userId) //调用子组件的方法 异步方法 强制等待执行完再弹层，就不会闪了
      this.showRoleDialog = true
    }
      

  }
}
</script>

<style>
/* .user-avatar {
          cursor: pointer;
           width: 50px;
          height: 50px;
        
          vertical-align: middle;
        } */
</style>